import { _decorator, instantiate, Label, Node, Prefab, Sprite, SpriteAtlas, TextAsset, v3} from 'cc';
import { UIComponent } from '../../../../Framework/Scripts/Managers/UIComponent';
import { AbNames, EventMsgKes } from '../../Config/ResConfig';
import { ResManager } from '../../../../Framework/Scripts/Managers/ResManager';
import { ExcelMgr } from '../../../../Framework/Scripts/Managers/ExcelMgr';
import { Answer, GameType, Respones, RewardType } from '../../Config/GameCfg';
import { UIMgr, UIType } from '../../../../Framework/Scripts/Managers/UIMgr';
import { GameEndTzWin_Ctr } from '../GameTZ/GameEndTzWin_Ctr';
import { GameEndTzLose_Ctr } from '../GameTZ/GameEndTzLose_Ctr';
import { GameUtils } from '../../../../Framework/Scripts/Utils/GameUtils';
import { ExitTip_Ctr } from '../ExitTip_Ctr';
import { ViewMgr } from '../../../../Framework/Scripts/Managers/ViewMgr';
import { GamePlayMap } from '../GamePlay/GamePlayMap';
import { IAnswerTzRes, IAnswerTzTimeOutRes, IAsTzEndGetRewardRes, IFuHuoRes, IGmaeSceneZtRes, INoticeCurRes, INoticeGameEnd, INoticeNext, IRdTz, Itopic } from '../proto/gameTz';
import { SceneMgr } from '../../../../Framework/Scripts/Managers/SceneMgr';
const { ccclass, property } = _decorator;

const EndCode = {
    isAll: 1, //全部答完，并且全对
    UnAll: 2,  //中间有错
}

/**
 * 每日挑战答题
 */
@ccclass('GamePlayTz_Ctr')
export class GamePlayTz_Ctr extends UIComponent {
    spBarbg: Node;      //显示答题进度
    labTime: Label;     //事件
    spTopicBg: Node;    //显示题目的背景  
    time: number;
    ts_map: GamePlayMap;

    groupTpxs:Itopic[]; //当前轮的题目数组
    topList: Node; //上面节奖励节点点
    spbar: Sprite;
    lastData: Itopic = null; //记录上一个数据，用于复活使用 
    atals: SpriteAtlas;

    protected onLoad(): void {
        console.log('======GamePlayTz_Ctr===onLoad======')
        this.InitUI();
        this.InitData();
        this.setBgAni(0);
    }

    start() {

    }

    protected onDestroy(): void {
        this.unRegisterEvent();
    }

    private InitUI(){
        this.registerEvent();

        this.spBarbg = this.ViewNode('spBarbg');
        this.labTime = this.ViewComponent('spTimeBg/labTime',Label);
        this.spTopicBg = this.ViewNode('ScrollView/view/content/spBg');

        this.topList = this.ViewNode('spBarbg/list');
        this.spbar = this.ViewComponent('spBarbg/spbar',Sprite);

        let map = this.ViewNode('map');
        let pre = ResManager.inst.getAsset(AbNames.GamePlay,'Prefabs/GamePlay/GameMap',Prefab);
        let item: any = instantiate(pre)
        item.parent = map;
        this.ts_map = item.addComponent(GamePlayMap) as GamePlayMap;
        this.ts_map.gameType = GameType.Game_TZ;
        this.AddButtonListener('btnBack',this,this.OnBtnCloseClick1);

        let txt = ResManager.inst.getAsset(AbNames.GamePlay,'Excle/DT',TextAsset) as TextAsset;
        ExcelMgr.inst.AddTable('DT',txt.text);
    }

    private InitData(){
        this.groupTpxs = [];
        //请求游戏场景
        // MsgDataGame.inst.GameSceneTzReq();

        this.atals = ResManager.inst.getAsset(AbNames.GamePlay,'Atals/GamePlay',SpriteAtlas) as SpriteAtlas;
    }

    private registerEvent(){
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgGameSceneTzRes,this.onGameSceneTzRes,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgStartAnswerTzRes,this.onStartAnswerTzRes,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgStartAnswerTzErrNotice,this.onStartAnswerTzErrNotice,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgStartAnswerTzTimeOutRes,this.onStartAnswerTzTimeOutRes,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgStartAnswerTzNextNotice,this.onStartAnswerTzNextNotice,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgStartAnswerTzEndNotice,this.onStartAnswerTzEndNotice,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgStartAnswerTzEndGetRewardRes,this.onStartAnswerTzEndGetRewardRes,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgStartAnswerTzFuHuoRes,this.onStartAnswerTzFuHuoRes,this);
    }

    private unRegisterEvent(){
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgGameSceneTzRes,this.onGameSceneTzRes,this);
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgStartAnswerTzRes,this.onStartAnswerTzRes,this);
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgStartAnswerTzErrNotice,this.onStartAnswerTzErrNotice,this);
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgStartAnswerTzTimeOutRes,this.onStartAnswerTzTimeOutRes,this);
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgStartAnswerTzNextNotice,this.onStartAnswerTzNextNotice,this);
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgStartAnswerTzEndNotice,this.onStartAnswerTzEndNotice,this);
        globalThis.gameMgr._eventTarget.off(EventMsgKes.msgStartAnswerTzEndGetRewardRes,this.onStartAnswerTzEndGetRewardRes,this);
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgStartAnswerTzFuHuoRes,this.onStartAnswerTzFuHuoRes,this);
    }

    private backHome(){
        const callFunction = SceneMgr.inst.SetCallFun(SceneMgr.inst.showHallViwe);
        let call ={
            func: callFunction,
            path: "Prefabs/GameHall"
        }
        ViewMgr.inst.ConnectToHall(call);
    }

    //返回
    private OnBtnCloseClick1(){
        let com = UIMgr.inst.ShowUIView(AbNames.GamePlay,'Prefabs/ExitTip',UIType.UnFull) as ExitTip_Ctr;
        com.setData(()=>{
            console.log('=======leftClick========')
            this.backHome();
        },()=>{
            console.log('=======rightClick========')
           
        },'您确定要退出游戏吗？')
    }

    private setBarData(curNum:number, total:number){
        let pre = curNum/total;
        this.spbar.fillRange = pre;
    }

    private stopTimeOut(){
        this.time = 0;
        this.unschedule(this.setTimeOut);
    }

    private setTimeOut(){
        if(this.time <= 0){
            this.unschedule(this.setTimeOut);
            //请求答题超时
            globalThis.gameMgr._GameTzMsg.StartAnswerTzTimeOutReq(this.ts_map.tid);
            return;
        }
        this.time--;
        this.labTime.string =this.time.toString(); 
    }

    //展示一个题目
    private showOneTopic(){
        if(this.groupTpxs.length <= 0){
            console.log('======当前组题目已经答完======');
            return;
        }
        let data:Itopic = this.groupTpxs.shift();
        console.log('========showOneTopic=========',data);
        this.time = data.time;

        this.lastData = GameUtils.deepClone(data);
        
        this.unschedule(this.setTimeOut);
        this.schedule(this.setTimeOut, 1);
        this.ts_map.showTopic(data.time,data.topicId,data.tidx);
    }

    //设置上面显示
    private setTopReward(list: IRdTz[]){
        console.log('========litem========',list);
        let temp:any = this.topList.children[0];
        for (let i = 0; i < list.length - 1; i++) {
            let item = instantiate(temp);
            this.topList.addChild(item);
            let xx = item.getPosition().x + (i+1)*213;
            item.setPosition(v3(xx,0,0));
        }

      
        let children = this.topList.children;
        for (let i = 0; i < children.length; i++) {
            let icon = children[i].getChildByPath('icon');
            let des = children[i].getChildByPath('lab');
            let cfg:IRdTz = list[i];
            let spICon = icon.getComponent(Sprite);
            let lab = des.getComponent(Label);

            lab.string = `x${cfg.rewardNum}`;
            if(cfg.rewardType === RewardType.Type_Quan){
                let sf = this.atals .getSpriteFrame('GamePlay_coin');
                if(sf){
                    spICon.spriteFrame = sf;
                }
            }
        }
    }

    //挑战赛游戏场景
    private onGameSceneTzRes(data:IGmaeSceneZtRes){
        console.log('=========onGamePlayTzRes===========',data);
   
        //显示题目信息
        if(this.hasProInObj(data,'topics')){
            this.groupTpxs = [...data.topics];
                this.showOneTopic();

            let num = 0;
            if(this.hasProInObj(data,'curNum')){
                this.setBarData(data.curNum,data.topics.length);
            }
        }

        //显示答对奖励信息
        if(this.hasProInObj(data,'listReward')){
            this.setTopReward(data.listReward);
        }
    }

    //用户答题返回
    private onStartAnswerTzRes(data: IAnswerTzRes){
        console.log('=======onStartAnswerTzRes=========');
        if(this.hasProInObj(data,'code')){
            this.stopTimeOut();
            if(data.code === Respones.OK){
                if(this.hasProInObj(data, 'status') && this.hasProInObj(data,'tid') && this.hasProInObj(data,'cid')){
                    if(data.status === Answer.Cur){ //答对
                        this.ts_map.setChoicesData(data.cid,true,true);
                    }else if(data.status === Answer.Err){ //答错
                        this.ts_map.setChoicesData(data.cid,false,true);
                    }
                }
            }
        }
    }

    //每日挑战用户答题失败通知正确结果
    private onStartAnswerTzErrNotice(data: INoticeCurRes){
        console.log('===========onStartAnswerTzErrNotice=============');
        if(this.hasProInObj(data,'cid')){
            this.ts_map.setCurrentChoice(data.cid);
        }
    }

    //用户答题超时返回
    private onStartAnswerTzTimeOutRes(data: IAnswerTzTimeOutRes){
        console.log('==========onStartAnswerTzTimeOutRes=============');
        if(this.hasProInObj(data,'cid')){
            this.ts_map.setCurrentChoice(data.cid);
        }
    }

    //通知下一题
    private onStartAnswerTzNextNotice(data: INoticeNext){
        console.log('==========onStartAnswerTzNextNotice=============');
        this.showOneTopic();
        if(this.hasProInObj(data,'curNum') && this.hasProInObj(data,'totalNum')){
            this.setBarData(data.curNum,data.totalNum);
        }
    }

    //结算通知
    private onStartAnswerTzEndNotice(data: INoticeGameEnd){
        console.log('==========onStartAnswerTzNextNotice=============');
        if(this.hasProInObj(data,'isAll')){
            let has = data.isAll;
            let reward = data.reward;
            if(has == EndCode.isAll){ //弹出领取奖励的界面
                console.log('========全部回答正确=======');
                let com = UIMgr.inst.ShowUIView(AbNames.GamePlay,'Prefabs/GameTZ/GameEndTzWin',UIType.UnFull) as GameEndTzWin_Ctr;
                com.setDate(reward);
            }else if(has == EndCode.UnAll){ 
                console.log('========中间有错误=======');
                let com = UIMgr.inst.ShowUIView(AbNames.GamePlay,'Prefabs/GameTZ/GameEndTzLose',UIType.UnFull) as GameEndTzLose_Ctr;
                com.setDate(reward);
            }
        }   
    }

    //结算领取奖励返回
    private onStartAnswerTzEndGetRewardRes(data: IAsTzEndGetRewardRes){
        console.log('======onStartAnswerTzEndGetRewardRes=======');
        if(this.hasProInObj(data,'code')){
            if(data.code == Respones.OK){
                this.backHome();
            }
        }
    }
    
    //复活
    private onStartAnswerTzFuHuoRes(data: IFuHuoRes){
        console.log('==========onStartAnswerTzFuHuoRes1=============',data.code,this.lastData);
        if(this.hasProInObj(data,'code')){
            if(data.code === Respones.OK){
                if(this.lastData){
                    this.groupTpxs.unshift(this.lastData);
                    this.lastData = null;
                    this.showOneTopic();
                }
            }
        }
    }
}